<template>
  <div class="home">
    <van-nav-bar
      :title="$route.meta.title"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <div class="search">
      <div class="flex">
        <van-row>
          <van-col span="24">
            <van-field
              v-model="requestParams.fixCenterName"
              name="维修中心"
              label="维修中心"
              input-align="right"
              readonly
              placeholder="请选择"
              right-icon="arrow"
              @click="handleSelect('fixCenterId', 'fixCenterName')"
            />
          </van-col>
          <van-col span="24">
            <van-field
              v-model="requestParams.brandName"
              name="品牌"
              label="品牌"
              input-align="right"
              placeholder="请选择"
              right-icon="arrow"
              readonly
              @click="handleSelect('brandId', 'brandName')"
            />
          </van-col>
        </van-row>
      </div>
      <van-field
        v-model="requestParams.taskStartCreateTime"
        label="任务生成时间"
        :placeholder="'请选择'"
        input-align="right"
        right-icon="arrow"
        readonly
        @click="handleSelectTime('taskStartCreateTime')"
        label-width="160px"
      />
      <van-field
        v-model="requestParams.taskEndCreateTime"
        label="任务结束时间"
        :placeholder="'请选择'"
        input-align="right"
        right-icon="arrow"
        readonly
        label-width="160px"
        @click="handleSelectTime('taskEndCreateTime')"
      />
      <div class="timebox">
        <van-field
          v-model="requestParams.taskTypeName"
          name="任务类型"
          label="任务类型"
          input-align="right"
          placeholder="请选择"
          readonly
          right-icon="arrow"
          @click="handleSelect('taskTypeId', 'taskTypeName')"
        />
        <van-field name="radio" label="统计类型" input-align="right">
          <template #input>
            <van-radio-group
              v-model="requestParams.countType"
              direction="horizontal"
            >
              <van-radio name="person">按人员</van-radio>
              <van-radio name="taskType">按任务类型</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-popup v-model="showSelectPicker" position="bottom">
          <van-picker
            show-toolbar
            :columns="columns"
            @confirm="handleSelectConfirm"
            @cancel="showSelectPicker = false"
            value-key="name"
          />
        </van-popup>
        <!-- 时间选择 -->
        <van-popup v-model="showPickerDate" position="bottom">
          <van-datetime-picker
            v-model="currentDate"
            type="date"
            @cancel="onCancelDate"
            @confirm="onConfirmDate"
            :formatter="formatter"
          />
        </van-popup>
      </div>
    </div>
    <div class="tableData">
      <table>
        <tr>
          <th>
            {{ requestParams.countType == "person" ? "人员姓名" : "任务名称" }}
          </th>
          <th>任务数</th>
          <th>处理数量</th>
          <th>战败任务数</th>
          <th>成功招揽数</th>
          <th>逾期数</th>
        </tr>
        <tbody v-if="dataList && dataList.length != 0">
          <tr v-for="(item, index) in dataList" :key="index">
            <td class="tab_item">
              {{
                requestParams.countType == "person"
                  ? item.personName
                  : item.taskName
              }}
            </td>
            <td>{{ item.taskCount }}</td>
            <td>{{ item.dealCount }}</td>
            <td>{{ item.failedCount }}</td>
            <td>{{ item.successCount }}</td>
            <td>{{ item.expeedPercent }}</td>
          </tr>
        </tbody>

        <tr>
          <td class="tab_item">{{ lastObj.name }}</td>
          <td>{{ lastObj.totTaskCount }}</td>
          <td>{{ lastObj.totDealCount }}</td>
          <td>{{ lastObj.totFailedCount }}</td>
          <td>{{ lastObj.totSuccessCount }}</td>
          <td>{{ lastObj.totExpeedPercent }}</td>
        </tr>
      </table>
    </div>
    <div class="loading" v-if="loading">
      <van-loading size="30px" class="loadbox" color="#fff" text-color="#fff">
        加载中...
      </van-loading>
      <div class="mask"></div>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import taskApi from "@/api/taskApi";
import commonApi from "@/api/commonApi";
import {
  getCookies,
  getCurrentTime,
  getCurrentFirstDay,
  isIOS,
} from "@/utils/util.js";
import { Toast } from "vant";

export default {
  name: "taskData",
  components: { Toast },
  data() {
    return {
      columns: [],
      showSelectPicker: false,
      requestParams: {
        countType: "person", //必填，person,taskType，对应按照人员或者任务类型
        brandId: "", //品牌ID
        pageNo: 1, //页数，每页默认500条
        fixCenterId: "", //维修中心IDString
        taskStartCreateTime: getCurrentFirstDay(), //任务开始创建时间 yyyy-MM-dd
        taskEndCreateTime: getCurrentTime(), //任务结束创建时间 yyyy-MM-dd
        taskTypeId: "", //任务类型ID，
        userId: getCookies("userId"), //用户ID，必填，String
      },

      repairCenterList: [
        { name: "厦门路虎", code: "1" },
        { name: "厦门捷豹", code: "2" },
      ],
      serviceList: [
        { name: "黄某某", code: "1" },
        { name: "张某某", code: "2" },
      ],

      timeField: "",
      field: "",
      fieldName: "",
      showPickerDate: false,
      currentDate: new Date(),
      dataList: [],
      lastObj: [],
      taskTypeList: [],
      fixCenterList: [],
      brandList: [],
      loading: false,
    };
  },
  watch: {
    requestParams: {
      handler: function (val, oldVal) {
        if (
          val.brandId ||
          val.fixCenterId ||
          val.taskStartCreateTime ||
          val.taskEndCreateTime ||
          val.taskTypeId ||
          val.countType
        ) {
          this.loadData();
        }
      },
      deep: true,
      immediate: false,
    },
  },

  mounted() {
    this.getMainFixCenter();
    this.getTaskType();
    this.loadData();
    console.log(isIOS());
  },

  methods: {
    onClickLeft() {
      this.$router.go(-1);
    },
    // 选择下拉
    handleSelect(field, fieldName) {
      if (field == "taskType") {
        this.columns = this.taskTypeList;
      } else if (field == "brandId") {
        if (!this.requestParams.fixCenterId) {
          Toast("请先选择维修中心");
          return;
        }
        this.columns = this.brandList;
      } else if (field == "fixCenterId") {
        this.columns = this.fixCenterList;
      }
      this.field = field;
      this.fieldName = fieldName;
      this.showSelectPicker = true;
    },

    // 获取维修中心
    getMainFixCenter() {
      commonApi
        .getMainFixCenter({
          fixCenterId: "",
          userId: this.userId,
          type: "fixCenter",
        })
        .then((res) => {
          if (res.data) {
            this.fixCenterList = res.data;
          }
        });
    },
    // 获取品牌
    getBrandByFixCenter() {
      commonApi
        .getBrandByFixCenter({
          fixCenterId: this.requestParams.fixCenterId,
          userId: this.userId,
        })
        .then((res) => {
          if (res.data) {
            this.brandList = res.data;
          }
        });
    },
    // 获取任务类型
    getTaskType() {
      commonApi
        .getTaskType({ userId: this.requestParams.userId })
        .then((res) => {
          this.taskTypeList = res.data;
        });
    },

    // 日期组件自定义格式
    formatter(type, value) {
      if (type === "year") {
        this.value1 = value; // 可以拿到当前点击的数值
        return `${value}年`;
      } else if (type === "month") {
        this.value2 = value;
        return `${value}月`;
      }
      this.value3 = value;
      return `${value}日`;
    },

    // 获取list名称
    getFieldName(list, key, val) {
      if (list && list.length > 0) {
        let obj = list.filter((item) => {
          return item[key] == val;
        });
        if (obj.length > 0) {
          return obj[0].name;
        }
      }
      return null;
    },
    // 选择下拉确认
    handleSelectConfirm(value, index) {
      this.requestParams[this.field] = value.billId;
      this.requestParams[this.fieldName] = value.name;
      if (this.field == "fixCenterId") {
        this.getBrandByFixCenter();
      }
      this.showSelectPicker = false;
    },
    // 时间筛选
    handleSelectTime(field) {
      this.timeField = field;
      this.showPickerDate = true;
    },
    // 时间确认
    onConfirmDate() {
      this.requestParams[
        this.timeField
      ] = `${this.value1}-${this.value2}-${this.value3}`; // 字符串拼接 结果入2020-07-03
      this.onCancelDate();
    },
    onCancelDate() {
      this.showPickerDate = false;
    },

    // 获取列表
    loadData() {
      this.loading = true;
      let dataList = [];
      taskApi.taskDataCal({ ...this.requestParams }).then((res) => {
        this.loading = false;
        if (res.data && res.data.length != 0) {
          res.data.forEach((item, index) => {
            if (index == res.data.length - 1) {
              this.lastObj = item;
            } else {
              dataList.push(item);
            }
          });
          this.dataList = dataList;
        }
      });
    },
  },
};
</script>

<style lang="less" scoped="">
.home {
  background: #f3f3f3;
}
.timebox {
  /deep/.van-cell::after {
    border: none;
  }
  .time_item {
    /deep/.van-field__control--right {
      border: 1px solid #d1d1d1;
      padding: 0.1rem 0;
      text-align: center;
      border-radius: 3px;
    }
  }
}

.timebox {
  /deep/.van-cell::after {
    border: none;
  }
  .time_item {
    /deep/.van-field__control--right {
      border: 1px solid #d1d1d1;
      padding: 0.1rem 0;
      text-align: center;
      border-radius: 3px;
    }
  }
}
.tableData {
  width: 100%;
  margin: auto;
  border-collapse: collapse;
  text-align: center;
  table {
    width: 100%;
    font-size: 0.24rem;
  }
  .tab_item {
    background: #f1f1f1;
  }
  tr {
    th {
      font-size: 0.24rem;
      border: 1px solid #ccc;
      padding: 0.2rem 0;
      background: #f1f1f1;
    }
    td {
      padding: 0.1rem 0;
      border: 1px solid #ccc;
      font-size: 0.24rem;
    }
  }
}
</style>
